package com.gla.market.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gla.market.R;
import com.gla.market.adapter.HistoryOrderShopAdapter;
import com.gla.market.constant.Constants;
import com.gla.market.entity.Order;
import com.gla.market.entity.OrderResponse;
import com.gla.market.fragments.Shopcart;
import com.gla.market.utils.NetUtil;
import com.gla.market.utils.SharedPreferencesUtil;

import org.w3c.dom.Text;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class HistoryOrderActivity extends AppCompatActivity{

    private Integer user_id;
    private HistoryOrderShopAdapter historyOrderShopAdapter;
    private TextView bt0;
    private TextView bt1;
    private TextView bt2;
    private TextView bt3;
    private TextView bt4;

    private TextView his_back;
    private List<TextView> bt_list = new ArrayList<>();
    private RecyclerView orderList;
    private Context mContext;
    private List<OrderResponse> orderData;
    private IntentFilter intentFilter;
    private Receiver receiver;
    private TextView no_data;
    private ProgressBar progressBar;
    int state_id;//标记是哪种历史订单

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history_order);
        mContext = this;
        user_id = (Integer) SharedPreferencesUtil.get(this,"userInfo","user_id",1);
        orderData = new ArrayList<>();
        Intent intent = getIntent();
        state_id = intent.getIntExtra("id",4);
        initView();
        initData();
        //广播接收器
        intentFilter = new IntentFilter();
        intentFilter.addAction("com.gla.market.DELETE_ORDER");
        intentFilter.addAction("com.gla.market.RECEIPT_ORDER");
        intentFilter.addAction("com.gla.market.PAY_ORDER");
        intentFilter.addAction("com.gla.market.CHARGE_BACK_ORDER");
        intentFilter.addAction("com.gla.market.EVALUATE_ORDER");
        intentFilter.addAction("com.gla.market.DELETE_ORDER");
        receiver = new Receiver();
        mContext.registerReceiver(receiver,intentFilter);

        //4表示全部订单
        if(state_id==4){
            bt0.setTextColor(Color.parseColor("#F97396"));
        } else if(state_id== Order.PLACED){
            bt1.setTextColor(Color.parseColor("#F97396"));
        } else if(state_id==Order.PAID){
            bt2.setTextColor(Color.parseColor("#F97396"));
        } else if(state_id==Order.SHIPPED){
            bt3.setTextColor(Color.parseColor("#F97396"));
        } else if(state_id==Order.RECEIVED){
            bt4.setTextColor(Color.parseColor("#F97396"));
        }
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        mContext.unregisterReceiver(receiver);
    }
    private void initData() {
        progressBar.setVisibility(View.VISIBLE);
        orderList.setVisibility(View.GONE);
        String url = Constants.BASE_URL + Constants.GET_ORDER + "?user_id=" + user_id + "&state_id=" + state_id;
        NetUtil.doGet(url, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                uiHandler.sendEmptyMessage(-1);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string().trim();
                JSONObject object = JSON.parseObject(result);
                Message message = Message.obtain();
                System.out.println(object);
                if (!object.getString("message").contains("JWT") && object.getString("error")==null && object.getInteger("code")==100) {
                    message.what = 1;
                    //解析拿到data中的lists数据
                    JSONArray lists = ((JSONArray) object.get("data"));
                    orderData = JSONArray.parseArray(JSON.toJSONString(lists), OrderResponse.class);
                } else {
                    message.what = 0;
                    message.obj = object.getString("message");
                }
                uiHandler.sendMessage(message);
            }
        });
    }

    private void initView() {
        his_back = (TextView) findViewById(R.id.his_back);
        bt0 = (TextView) findViewById(R.id.bt0);bt_list.add(bt0);
        bt1 = (TextView) findViewById(R.id.bt1);bt_list.add(bt1);
        bt2 = (TextView) findViewById(R.id.bt2);bt_list.add(bt2);
        bt3 = (TextView) findViewById(R.id.bt3);bt_list.add(bt3);
        bt4 = (TextView) findViewById(R.id.bt4);bt_list.add(bt4);
        no_data = (TextView) findViewById(R.id.no_data);
        progressBar = (ProgressBar) findViewById(R.id.order_progress);
        View.OnClickListener btListen = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                for(TextView item : bt_list){
                    item.setTextColor(Color.BLACK);
                }
                if(view.getId() == R.id.bt0){
                    state_id = 4;
                    bt0.setTextColor(Color.parseColor("#F97396"));
                } else if(view.getId() == R.id.bt1){
                    state_id = Order.PLACED;
                    bt1.setTextColor(Color.parseColor("#F97396"));
                } else if(view.getId() == R.id.bt2){
                    state_id = Order.PAID;
                    bt2.setTextColor(Color.parseColor("#F97396"));
                } else if(view.getId() == R.id.bt3){
                    state_id = Order.SHIPPED;
                    bt3.setTextColor(Color.parseColor("#F97396"));
                } else if(view.getId() == R.id.bt4){
                    state_id = Order.RECEIVED;
                    bt4.setTextColor(Color.parseColor("#F97396"));
                }
                initData();
            }
        };
        bt0.setOnClickListener(btListen);
        bt1.setOnClickListener(btListen);
        bt2.setOnClickListener(btListen);
        bt3.setOnClickListener(btListen);
        bt4.setOnClickListener(btListen);
        orderList = (RecyclerView) findViewById(R.id.his_order_list);
        orderList.setLayoutManager(new LinearLayoutManager(mContext));
        orderList.addItemDecoration(new SpaceItemDecoration(20));
        historyOrderShopAdapter = new HistoryOrderShopAdapter(mContext);
        orderList.setAdapter(historyOrderShopAdapter);
        his_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    private Handler uiHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case -2:
                    //未登录，需要登录！
                    Toast.makeText(mContext, "您还未登录！请先登录！", Toast.LENGTH_SHORT).show();
                    break;
                case -1:
                    //网络请求失败
                    Toast.makeText(mContext, "网络请求失败！"
                            , Toast.LENGTH_SHORT).show();
                    break;
                case 0:
                    //网络请求成功，但是返回状态为失败
                    Toast.makeText(mContext, msg.obj == null ? "请求处理失败！获取订单数据失败！"
                            : msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    progressBar.setVisibility(View.GONE);
                    orderList.setVisibility(View.VISIBLE);
                    if(orderData.size()==0){
                        no_data.setVisibility(View.VISIBLE);
                    } else {
                        no_data.setVisibility(View.GONE);
                    }
                    //设置Adapter
                    historyOrderShopAdapter.setData(orderData);
                    break;
                case 2:
                    int id = (int)msg.obj;
                    for(int i=0;i<orderData.size();i++){
                        if(orderData.get(i).getOrder().getId()==id){
                            orderData.remove(i);
                            historyOrderShopAdapter.notifyDataSetChanged();
                            Toast.makeText(mContext, "删除订单成功!", Toast.LENGTH_SHORT).show();
                            break;
                        }
                    }
                    break;
                case 3:
                    initData();
                    Toast.makeText(mContext, "退单成功!", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent("com.gla.market.UPDATE_ABOUT_ME");
                    mContext.sendBroadcast(intent);
                    break;
                case 4:
                    initData();
                    showMoney();
                    break;
                case 5:
                    double money = (int)msg.obj;
                    Toast.makeText(mContext, "支付成功!余额:"+money + "元", Toast.LENGTH_SHORT).show();
                    initData();
                    break;
                case 6:
                    Toast.makeText(mContext, "支付失败!"+msg.obj, Toast.LENGTH_SHORT).show();
                    break;
                case 7:
                    Toast.makeText(mContext, "已发起申请退款，请等待同意！", Toast.LENGTH_SHORT).show();
                    initData();
                    break;
                case 8:
                    Toast.makeText(mContext, "收货成功！", Toast.LENGTH_SHORT).show();
                    initData();
                    break;
                case 9:
                    Toast.makeText(mContext, "评价成功！", Toast.LENGTH_SHORT).show();
                    initData();
                    break;
                default:
                    break;
            }

        }
    };

    public void showMoney() {
        String url = Constants.BASE_URL + Constants.GET_USER_MONEY+"/"+user_id;
        NetUtil.doGet(url, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(mContext, "请求失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string().trim();
                JSONObject object = JSON.parseObject(result);
                Message message = Message.obtain();
                System.out.println(object);
                if (!object.getString("message").contains("JWT") && object.getString("error")==null && object.getInteger("code")==100) {
                    message.what = 5;
                    message.obj = object.getInteger("data");
                } else {
                    message.what = 6;
                    message.obj = object.getString("message");
                }
                uiHandler.sendMessage(message);
            }
        });
    }

    class Receiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals("com.gla.market.DELETE_ORDER")){
                int order_id = intent.getIntExtra("order_id",-1);
                String url = Constants.BASE_URL + Constants.GET_DELETE_ORDER + "?order_id=" + order_id;
                NetUtil.doGet(url, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Toast.makeText(context, "请求失败", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string().trim();
                        JSONObject object = JSON.parseObject(result);
                        Message message = Message.obtain();
                        System.out.println(object);
                        if (!object.getString("message").contains("JWT") && object.getString("error")==null && object.getInteger("code")==100) {
                            message.what = 2;
                            message.obj = object.getInteger("data");
                        } else {
                            message.what = 0;
                            message.obj = object.getString("message");
                        }
                        uiHandler.sendMessage(message);
                    }
                });
            } else if(intent.getAction().equals("com.gla.market.RECEIPT_ORDER")) {
                //收货监听
                int order_id = intent.getIntExtra("order_id",-1);
                String url = Constants.BASE_URL + Constants.GET_CHANGE_ORDER_STATE + "?order_id=" + order_id +"&state="+Order.RECEIVED;
                NetUtil.doGet(url, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Toast.makeText(context, "请求失败", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string().trim();
                        JSONObject object = JSON.parseObject(result);
                        Message message = Message.obtain();
                        System.out.println(object);
                        if (!object.getString("message").contains("JWT") && object.getString("error")==null && object.getInteger("code")==100) {
                            message.what = 8;
                        } else {
                            message.what = 0;
                            message.obj = object.getString("message");
                        }
                        uiHandler.sendMessage(message);
                    }
                });
            } else if(intent.getAction().equals("com.gla.market.PAY_ORDER")) {
                //支付监听
                int order_id = intent.getIntExtra("order_id",-1);
                String url = Constants.BASE_URL + Constants.GET_CHANGE_ORDER_STATE + "?order_id=" + order_id +"&state="+Order.PAID;
                NetUtil.doGet(url, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Toast.makeText(context, "请求失败", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string().trim();
                        JSONObject object = JSON.parseObject(result);
                        Message message = Message.obtain();
                        System.out.println(object);
                        if (!object.getString("message").contains("JWT") && object.getString("error")==null && object.getInteger("code")==100) {
                            message.what = 4;
                        } else {
                            message.what = 0;
                            message.obj = object.getString("message");
                        }
                        uiHandler.sendMessage(message);
                    }
                });

            } else if(intent.getAction().equals("com.gla.market.CHARGE_BACK_ORDER")) {
                //退单监听
                int order_id = intent.getIntExtra("order_id",-1);
                //如果是已支付，还未发货，直接退款
                for(OrderResponse item : orderData) {
                    if(order_id == item.getOrder().getId()) {
                        if (item.getOrder().getState() == Order.PAID) {
                            Log.d("调试", "未发货，直接退款");
                            String url = Constants.BASE_URL + Constants.GET_CHANGE_ORDER_STATE + "?order_id=" + order_id + "&state=" + Order.REFUNDED;
                            NetUtil.doGet(url, new Callback() {
                                @Override
                                public void onFailure(Call call, IOException e) {
                                    Toast.makeText(context, "请求失败", Toast.LENGTH_SHORT).show();
                                }

                                @Override
                                public void onResponse(Call call, Response response) throws IOException {
                                    String result = response.body().string().trim();
                                    JSONObject object = JSON.parseObject(result);
                                    Message message = Message.obtain();
                                    System.out.println(object);
                                    if (!object.getString("message").contains("JWT") && object.getString("error") == null && object.getInteger("code") == 100) {
                                        message.what = 3;
                                    } else {
                                        message.what = 0;
                                        message.obj = object.getString("message");
                                    }
                                    uiHandler.sendMessage(message);
                                }
                            });
                        }
                        else if(item.getOrder().getState() == Order.SHIPPED) {
                            Log.d("调试", "已发货，申请退款，等待审批");
                            String url = Constants.BASE_URL + Constants.GET_CHANGE_ORDER_STATE + "?order_id=" + order_id + "&state=" + Order.CHARGEBACK;
                            NetUtil.doGet(url, new Callback() {
                                @Override
                                public void onFailure(Call call, IOException e) {
                                    Toast.makeText(context, "请求失败", Toast.LENGTH_SHORT).show();
                                }

                                @Override
                                public void onResponse(Call call, Response response) throws IOException {
                                    String result = response.body().string().trim();
                                    JSONObject object = JSON.parseObject(result);
                                    Message message = Message.obtain();
                                    System.out.println(object);
                                    if (!object.getString("message").contains("JWT") && object.getString("error") == null && object.getInteger("code") == 100) {
                                        message.what = 7;
                                    } else {
                                        message.what = 0;
                                        message.obj = object.getString("message");
                                    }
                                    uiHandler.sendMessage(message);
                                }
                            });
                        }
                    }
                }

            } else if(intent.getAction().equals("com.gla.market.EVALUATE_ORDER")) {
                //评价监听
                int order_id = intent.getIntExtra("order_id",-1);
                String evaluation = intent.getStringExtra("evaluation");
                int ratting = intent.getIntExtra("point",1);
                String url = Constants.BASE_URL + "/evaluation/add" + "?order_id=" + order_id +"&evaluation="+evaluation+"&ratting="+ratting;
                NetUtil.doGet(url, new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Toast.makeText(context, "请求失败", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String result = response.body().string().trim();
                        JSONObject object = JSON.parseObject(result);
                        Message message = Message.obtain();
                        System.out.println(object);
                        if (!object.getString("message").contains("JWT") && object.getString("error") == null && object.getInteger("code") == 100) {
                            message.what = 9;
                        } else {
                            message.what = 0;
                            message.obj = object.getString("message");
                        }
                        uiHandler.sendMessage(message);
                    }
                });
            }
        }
    }

    //修改RecyclerView Item间隔的辅助类
    class SpaceItemDecoration extends RecyclerView.ItemDecoration {
        int mSpace;
        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            outRect.bottom = mSpace;
            if (parent.getChildAdapterPosition(view) == 0) {
                outRect.top = mSpace/2;
            }
            outRect.left = outRect.right = 15;
        }

        public SpaceItemDecoration(int space) {
            this.mSpace = space;
        }
    }
}